package com.qinglei.recoup.app.service.impl;

import com.aliyun.iot20180120.models.ListOTAModuleVersionsByDeviceResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.app.dao.RadarWechatAppMapper;
import com.qinglei.recoup.app.dao.RadarWechatAppSubscriptionMapper;
import com.qinglei.recoup.app.dao.WxDetailedMapper;
import com.qinglei.recoup.app.domain.RadarWechatApp;
import com.qinglei.recoup.app.domain.RadarWechatAppSubscription;
import com.qinglei.recoup.app.domain.WxDetailed;
import com.qinglei.recoup.app.pojo.RadarWechatAppSubscriptionEnum;
import com.qinglei.recoup.app.pojo.SubscribeParam;
import com.qinglei.recoup.app.pojo.TagParam;
import com.qinglei.recoup.app.service.AppRadarService;
import com.qinglei.recoup.app.util.WxUtil;
import com.qinglei.recoup.common.domain.CommonConstant;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.exception.RedisConnectException;
import com.qinglei.recoup.common.properties.CuserProperties;
import com.qinglei.recoup.common.service.RedisService;
import com.qinglei.recoup.common.service.impl.ProductCache;
import com.qinglei.recoup.common.tenant.TenantContextHolder;
import com.qinglei.recoup.common.utils.RecoupUtil;
import com.qinglei.recoup.hmp.domain.HmpUserBindDevice;
import com.qinglei.recoup.hmp.pojo.dto.AddUserBindDeviceDTO;
import com.qinglei.recoup.hmp.pojo.vo.BindUserTagParam;
import com.qinglei.recoup.hmp.service.HmpDeviceService;
import com.qinglei.recoup.hmp.service.HmpUserBindDeviceService;
import com.qinglei.recoup.hmp.service.HmpUserTagService;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.pojo.AddRadarParam;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.RadarBedService;
import com.qinglei.recoup.system.service.RadarService;
import lombok.ToString;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.qinglei.recoup.app.dao.WxDetailedMapper;

@Service
public class AppRadarServiceImpl implements AppRadarService {
    @Resource
    private RadarService radarService;

    @Resource
    private BedService bedService;

    @Resource
    private RadarBedService radarBedService;

    @Resource
    private CuserProperties cuserProperties;

    @Value("${wxxcx.appId}")
    private  String APPID ;

    @Value("${wxxcx.appSecret}")
    private  String SECRET;

    @Resource
    private WxDetailedMapper wxDetailedMapper;

    @Resource
    private RadarWechatAppMapper radarWechatAppMapper;

    @Autowired
    private RadarWechatAppSubscriptionMapper radarWechatAppSubscriptionMapper;

    @Autowired
    private HmpDeviceService hmpDeviceService;

    @Autowired
    private HmpUserBindDeviceService hmpUserBindDeviceService;


    @Autowired
    private ProductCache productCache;

    @Override
    @Transactional
    public CommonRes appAddRadar(AddRadarParam addRadarParam)  {
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("snCode",addRadarParam.getSnCode());
        Integer tenantId = TenantContextHolder.getTenantId();
        String iotProductKey = null;
        TenantContextHolder.clear();
        Radar radarOld = radarService.getBaseMapper().selectOne(Wrappers.<Radar>lambdaQuery().eq(Radar::getSnCode, addRadarParam.getSnCode()).eq(Radar::getIsDeleted,0));
        Long userId = RecoupUtil.getCurrentUser().getId();
      /*  QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(addRadarParam.getSnCode(),"device_sn"); //
        queryWrapper.eq(userId,"user_id");
        queryWrapper.eq(0,"is_delete");
        Wrappers.<HmpUserBindDevice>lambdaQuery().eq(HmpUserBindDevice::getDeviceSn,addRadarParam.getSnCode())
                .eq(HmpUserBindDevice::getUserId,userId)
                .eq(HmpUserBindDevice::getIsDeleted,0);*/
        int hmpUserBindDeviceOld = hmpUserBindDeviceService.count(Wrappers.<HmpUserBindDevice>lambdaQuery().eq(HmpUserBindDevice::getDeviceSn,addRadarParam.getSnCode())
                .eq(HmpUserBindDevice::getUserId,userId)
                .eq(HmpUserBindDevice::getIsDeleted,0));

        if(hmpUserBindDeviceOld>0){
            resultMap.put("msgCode",2);
            resultMap.put("msg","SN号已绑定,请检查SN号");
            return CommonRes.ok(resultMap);
        }



        if (radarOld!=null && radarOld.getTenantId() != tenantId) {
            resultMap.put("msgCode",4);
            resultMap.put("msg","SN号已被其他机构绑定，请检查SN号");
            return CommonRes.failed(resultMap);
        }

        if (radarOld!=null && radarOld.getTenantId() == tenantId) {
            Bed bedTmp = bedService.getBedBySn(addRadarParam.getSnCode());
            AddUserBindDeviceDTO param = new AddUserBindDeviceDTO();
            param.setUserId(userId);
            param.setSn(addRadarParam.getSnCode());
            param.setBedId(bedTmp.getId());
            try {
                Map<String,Object> equipmentProductsMap = productCache.isExistEquipmentProducts(addRadarParam.getSnCode());
                boolean existEquipmentProducts = Boolean.valueOf(equipmentProductsMap.get("isExistEquipment").toString());
                iotProductKey = (String) equipmentProductsMap.get("productKey");
                param.setIotProductKey(iotProductKey);
                hmpDeviceService.addHmpDevice(param);
//              resultMap.put("msgCode",1);
//              resultMap.put("msg","设备绑定成功！SN号："+addRadarParam.getSnCode());
                resultMap.put("msgCode",2);
                resultMap.put("msg","SN号已绑定,请检查SN号");
                return CommonRes.ok(resultMap);
            }catch (Exception ex){
                ex.printStackTrace();
            }


        }

        try {
            Map<String,Object> equipmentProductsMap = productCache.isExistEquipmentProducts(addRadarParam.getSnCode());
            boolean existEquipmentProducts = Boolean.valueOf(equipmentProductsMap.get("isExistEquipment").toString());
            iotProductKey = (String) equipmentProductsMap.get("productKey");
            if(!existEquipmentProducts){
                resultMap.put("msgCode",3);
                resultMap.put("msg","SN号在物联网上不存在，请检查SN号");
                return CommonRes.failed(resultMap);
            }
        } catch (RedisConnectException e) {
            e.printStackTrace();
        }

        TenantContextHolder.setTenantId(tenantId);
        Radar radar = new Radar();
        BeanUtils.copyProperties(addRadarParam, radar);
        //获取设备的版本号
        try {
            ListOTAModuleVersionsByDeviceResponseBody.ListOTAModuleVersionsByDeviceResponseBodyData listOTAModuleVersionsByDeviceResponseBodyData
                    = productCache.selectDeviceOtaModleList(iotProductKey, addRadarParam.getSnCode());
            if(null != listOTAModuleVersionsByDeviceResponseBodyData && CollectionUtils.isNotEmpty(listOTAModuleVersionsByDeviceResponseBodyData.getSimpleOTAModuleInfo())){
                listOTAModuleVersionsByDeviceResponseBodyData.getSimpleOTAModuleInfo().forEach(simpleOTAModuleInfo->{
                    if("MCU".equals(simpleOTAModuleInfo.getModuleName())){
                        radar.setCurrentVersion(simpleOTAModuleInfo.getModuleVersion());
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        boolean save = radarService.save(radar);
        if (!save) {
            throw  new RuntimeException("新增监测仪失败！");
        }

        Bed bed = appAddBedBindRadar(radar);
        AddUserBindDeviceDTO param = new AddUserBindDeviceDTO();
        param.setUserId(userId);
        param.setSn(addRadarParam.getSnCode());
        param.setBedId(bed.getId());
        param.setIotProductKey(iotProductKey);
        hmpDeviceService.addHmpDevice(param);
        resultMap.put("msgCode",1);
        resultMap.put("msg","设备绑定成功！SN号："+addRadarParam.getSnCode());
        return CommonRes.ok(resultMap);

    }

    /**
     *
     * @param radar
     */
    private Bed appAddBedBindRadar(Radar radar){
        Bed bed = new Bed();
        bed.setBuildingId(cuserProperties.getBuildingId());
        bed.setFloorId(cuserProperties.getFloorId());
        bed.setRoomId(cuserProperties.getRoomId());
        bed.setName(radar.getSnCode());
        bed.setOutBedTimeout(cuserProperties.getOutBedTimeout());
        if (!bedService.save(bed)) {
            throw  new RuntimeException("添加床位失败！");
        }

        RadarBed radarBed = new RadarBed();
        radarBed.setBedId(bed.getId());
        radarBed.setRadarId(radar.getId());
        if (!radarBedService.save(radarBed)) {
            throw  new RuntimeException("设置床位设备绑定关系失败！");
        }

        return bed;

    }

    @Override
    public CommonRes removeAddRadar(AddRadarParam addRadarParam) {

        if(!isSnLegitimate(addRadarParam.getSnCode())){
            return CommonRes.failed("查询床位信息有误");
        }
        String unionid = RecoupUtil.getCurrentUser().getUnionid();
        if(StringUtils.isEmpty(unionid)){
            return CommonRes.failed("获取用户信息有误！unionid为空");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("unionid",unionid);
        WxDetailed wxDetailed =  wxDetailedMapper.selectOne(queryWrapper);
        if(wxDetailed==null){
            return CommonRes.failed("尚未关注清雷微信公众平台");
        }
        QueryWrapper wrapperRadarWechatApp = new QueryWrapper();
        wrapperRadarWechatApp.eq("open_id",wxDetailed.getOpenid());
        wrapperRadarWechatApp.eq("sn_code",addRadarParam.getSnCode());
        wrapperRadarWechatApp.eq("is_deleted",0);
        RadarWechatApp radarWechatAppOld = radarWechatAppMapper.selectOne(wrapperRadarWechatApp);
        if(radarWechatAppOld==null){
            return CommonRes.failed("未绑定SN"+addRadarParam.getSnCode()+"的设备");
        }
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("is_deleted",1);
        updateWrapper.eq("open_id",wxDetailed.getOpenid());
        updateWrapper.eq("sn_code",addRadarParam.getSnCode());
        radarWechatAppMapper.update(null,updateWrapper);
        radarWechatAppSubscriptionMapper.update(null,updateWrapper);
        return CommonRes.ok("解绑成功");
    }

    @Override
    @Transactional
    public CommonRes setTag(TagParam tagParam) {

        if(!isSnLegitimate(tagParam.getSnCode())){
            return CommonRes.failed("查询床位信息有误");
        }
        try {
            String unionid = RecoupUtil.getCurrentUser().getUnionid();
            if(StringUtils.isEmpty(unionid)){
                return CommonRes.failed("获取用户信息有误！unionid为空");
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("unionid",unionid);
            WxDetailed wxDetailed =  wxDetailedMapper.selectOne(queryWrapper);
            if(wxDetailed==null){
                return CommonRes.failed("尚未关注清雷微信公众平台");
            }
            QueryWrapper wrapperRadarWechatApp = new QueryWrapper();
            wrapperRadarWechatApp.eq("open_id",wxDetailed.getOpenid());
            wrapperRadarWechatApp.eq("sn_code",tagParam.getSnCode());
            wrapperRadarWechatApp.eq("is_deleted",0);
            RadarWechatApp radarWechatAppOld = radarWechatAppMapper.selectOne(wrapperRadarWechatApp);
            if(radarWechatAppOld!=null){
                return CommonRes.failed("已为该设备"+tagParam.getSnCode()+"设置标签"+radarWechatAppOld.getTag());
            }

            QueryWrapper wrapperDefaultRadarWechatApp = new QueryWrapper();
            wrapperDefaultRadarWechatApp.eq("open_id",wxDetailed.getOpenid());
            wrapperDefaultRadarWechatApp.eq("is_default",1);
            RadarWechatApp   defaultRadarWechatApp  =   radarWechatAppMapper.selectOne(wrapperDefaultRadarWechatApp);

            RadarWechatApp radarWechatApp = new RadarWechatApp();
            if(defaultRadarWechatApp==null){
                radarWechatApp.setIsDefault(1);
            }else{
                radarWechatApp.setIsDefault(0);
            }
            radarWechatApp.setSnCode(tagParam.getSnCode());
            radarWechatApp.setTag(tagParam.getTag());
            radarWechatApp.setOpenId(wxDetailed.getOpenid());
            radarWechatAppMapper.insert(radarWechatApp);
            SubscribeParam subscribeParam = new SubscribeParam();
            subscribeParam.setIsSubscribeAlarm(1);
            subscribeParam.setIsSubscribeDayDaily(1);
            subscribeParam.setSnCode(tagParam.getSnCode());
            setSubscribe(subscribeParam);
        }catch (Exception ex){
            ex.printStackTrace();
            return CommonRes.failed("获取微信详细信息有误");
        }

        return CommonRes.ok("成功");
    }



    @Override
    @Transactional
    public CommonRes setSubscribe(SubscribeParam subscribeParam){
        if(!isSnLegitimate(subscribeParam.getSnCode())){
            return CommonRes.failed("查询床位信息有误");
        }
        if(subscribeParam.getIsSubscribeAlarm()==null && subscribeParam.getIsSubscribeDayDaily()==null){
            return CommonRes.failed("请设置订阅类型");
        }
        String snCode = subscribeParam.getSnCode();
        try {
            String unionid = RecoupUtil.getCurrentUser().getUnionid();
            if(StringUtils.isEmpty(unionid)){
                return CommonRes.failed("获取用户信息有误！unionid为空");
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("unionid",unionid);
            WxDetailed wxDetailed =  wxDetailedMapper.selectOne(queryWrapper);
            if(wxDetailed==null){
                return CommonRes.failed("尚未关注清雷微信公众平台");
            }

            //查询是否绑定设备
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("sn_code",subscribeParam.getSnCode());
            queryWrapper1.eq("open_id",wxDetailed.getOpenid());
            queryWrapper1.eq("is_deleted",0);

            RadarWechatApp  radarWechatApp = radarWechatAppMapper.selectOne(queryWrapper1);
            if(radarWechatApp==null){
                return CommonRes.failed("未绑定sn号为："+snCode+"的设备");
            }

            RadarWechatAppSubscription radarWechatAppSubscription = new RadarWechatAppSubscription();
            radarWechatAppSubscription.setSnCode(snCode);
            radarWechatAppSubscription.setOpenId(wxDetailed.getOpenid());

            //订阅日报
            if(subscribeParam.getIsSubscribeDayDaily()!=null && subscribeParam.getIsSubscribeDayDaily()==1){
                QueryWrapper queryWrapperRadarWechatAppSubscription = new QueryWrapper();
                queryWrapperRadarWechatAppSubscription.eq("sn_code",subscribeParam.getSnCode());
                queryWrapperRadarWechatAppSubscription.eq("open_id",wxDetailed.getOpenid());
                queryWrapperRadarWechatAppSubscription.eq("is_deleted",0);
                queryWrapperRadarWechatAppSubscription.eq("type",RadarWechatAppSubscriptionEnum.DAILY.getCode());
                RadarWechatAppSubscription radarWechatAppSubscriptionOld =   radarWechatAppSubscriptionMapper.selectOne(queryWrapperRadarWechatAppSubscription);
                if(radarWechatAppSubscriptionOld!=null){
                    return CommonRes.failed("已订阅设备号"+snCode+"的"+RadarWechatAppSubscriptionEnum.DAILY.getName());
                }
                radarWechatAppSubscription.setType(RadarWechatAppSubscriptionEnum.DAILY.getCode());
                radarWechatAppSubscriptionMapper.insert(radarWechatAppSubscription);
            }
            //订阅报警
            if(subscribeParam.getIsSubscribeAlarm()!=null && subscribeParam.getIsSubscribeAlarm()==1){
                QueryWrapper queryWrapperRadarWechatAppSubscription = new QueryWrapper();
                queryWrapperRadarWechatAppSubscription.eq("sn_code",subscribeParam.getSnCode());
                queryWrapperRadarWechatAppSubscription.eq("open_id",wxDetailed.getOpenid());
                queryWrapperRadarWechatAppSubscription.eq("is_deleted",0);
                queryWrapperRadarWechatAppSubscription.eq("type",RadarWechatAppSubscriptionEnum.ALARM.getCode());
                RadarWechatAppSubscription radarWechatAppSubscriptionOld =   radarWechatAppSubscriptionMapper.selectOne(queryWrapperRadarWechatAppSubscription);
                if(radarWechatAppSubscriptionOld!=null){
                    return CommonRes.failed("已订阅设备号"+snCode+"的"+RadarWechatAppSubscriptionEnum.ALARM.getName());
                }
                radarWechatAppSubscription.setType(RadarWechatAppSubscriptionEnum.ALARM.getCode());
                radarWechatAppSubscriptionMapper.insert(radarWechatAppSubscription);
            }
            //订阅日报
            if(subscribeParam.getIsSubscribeDayDaily()!=null && subscribeParam.getIsSubscribeDayDaily()==0){
                QueryWrapper queryWrapperRadarWechatAppSubscription = new QueryWrapper();
                queryWrapperRadarWechatAppSubscription.eq("sn_code",subscribeParam.getSnCode());
                queryWrapperRadarWechatAppSubscription.eq("open_id",wxDetailed.getOpenid());
                queryWrapperRadarWechatAppSubscription.eq("is_deleted",0);
                queryWrapperRadarWechatAppSubscription.eq("type",RadarWechatAppSubscriptionEnum.DAILY.getCode());
                RadarWechatAppSubscription radarWechatAppSubscriptionOld =   radarWechatAppSubscriptionMapper.selectOne(queryWrapperRadarWechatAppSubscription);
                if(radarWechatAppSubscriptionOld==null){
                    return CommonRes.failed("未订阅设备号"+snCode+"的"+RadarWechatAppSubscriptionEnum.DAILY.getName());
                }
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id",radarWechatAppSubscriptionOld.getId());
                updateWrapper.set("is_deleted",1);
                radarWechatAppSubscriptionMapper.update(null,updateWrapper);
            }
            //订阅报警
            if(subscribeParam.getIsSubscribeAlarm()!=null && subscribeParam.getIsSubscribeAlarm()==0){
                QueryWrapper queryWrapperRadarWechatAppSubscription = new QueryWrapper();
                queryWrapperRadarWechatAppSubscription.eq("sn_code",subscribeParam.getSnCode());
                queryWrapperRadarWechatAppSubscription.eq("open_id",wxDetailed.getOpenid());
                queryWrapperRadarWechatAppSubscription.eq("is_deleted",0);
                queryWrapperRadarWechatAppSubscription.eq("type",RadarWechatAppSubscriptionEnum.ALARM.getCode());
                RadarWechatAppSubscription radarWechatAppSubscriptionOld =   radarWechatAppSubscriptionMapper.selectOne(queryWrapperRadarWechatAppSubscription);
                if(radarWechatAppSubscriptionOld==null){
                    return CommonRes.failed("未订阅设备号"+snCode+"的"+RadarWechatAppSubscriptionEnum.ALARM.getName());
                }
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id",radarWechatAppSubscriptionOld.getId());
                updateWrapper.set("is_deleted",1);
                radarWechatAppSubscriptionMapper.update(null,updateWrapper);
            }
        }catch (Exception e){
            e.printStackTrace();
            return CommonRes.failed("设置订阅异常");
        }
        return CommonRes.ok("设置订阅成功");
    }

    @Override
    public CommonRes cancelSubscribe(SubscribeParam subscribeParam) {
        if(!isSnLegitimate(subscribeParam.getSnCode())){
            return CommonRes.failed("查询床位信息有误");
        }
        if(subscribeParam.getIsSubscribeAlarm()==null && subscribeParam.getIsSubscribeDayDaily()==null){
            return CommonRes.failed("请设置取消订阅类型");
        }
        String snCode = subscribeParam.getSnCode();

        try {

            String unionid = RecoupUtil.getCurrentUser().getUnionid();
            if(StringUtils.isEmpty(unionid)){
                return CommonRes.failed("获取用户信息有误！unionid为空");
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("unionid",unionid);
            WxDetailed wxDetailed =  wxDetailedMapper.selectOne(queryWrapper);
            if(wxDetailed==null){
                return CommonRes.failed("尚未关注清雷微信公众平台");
            }

            //订阅日报
            if(subscribeParam.getIsSubscribeDayDaily()!=null && subscribeParam.getIsSubscribeDayDaily()==0){
                QueryWrapper queryWrapperRadarWechatAppSubscription = new QueryWrapper();
                queryWrapperRadarWechatAppSubscription.eq("sn_code",subscribeParam.getSnCode());
                queryWrapperRadarWechatAppSubscription.eq("open_id",wxDetailed.getOpenid());
                queryWrapperRadarWechatAppSubscription.eq("is_deleted",0);
                queryWrapperRadarWechatAppSubscription.eq("type",RadarWechatAppSubscriptionEnum.DAILY.getCode());
                RadarWechatAppSubscription radarWechatAppSubscriptionOld =   radarWechatAppSubscriptionMapper.selectOne(queryWrapperRadarWechatAppSubscription);
                if(radarWechatAppSubscriptionOld==null){
                    return CommonRes.failed("未订阅设备号"+snCode+"的"+RadarWechatAppSubscriptionEnum.DAILY.getName());
                }
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id",radarWechatAppSubscriptionOld.getId());
                updateWrapper.set("is_deleted",1);
                radarWechatAppSubscriptionMapper.update(null,updateWrapper);
            }
            //订阅报警
            if(subscribeParam.getIsSubscribeAlarm()!=null && subscribeParam.getIsSubscribeAlarm()==0){
                QueryWrapper queryWrapperRadarWechatAppSubscription = new QueryWrapper();
                queryWrapperRadarWechatAppSubscription.eq("sn_code",subscribeParam.getSnCode());
                queryWrapperRadarWechatAppSubscription.eq("open_id",wxDetailed.getOpenid());
                queryWrapperRadarWechatAppSubscription.eq("is_deleted",0);
                queryWrapperRadarWechatAppSubscription.eq("type",RadarWechatAppSubscriptionEnum.ALARM.getCode());
                RadarWechatAppSubscription radarWechatAppSubscriptionOld =   radarWechatAppSubscriptionMapper.selectOne(queryWrapperRadarWechatAppSubscription);
                if(radarWechatAppSubscriptionOld==null){
                    return CommonRes.failed("未订阅设备号"+snCode+"的"+RadarWechatAppSubscriptionEnum.ALARM.getName());
                }
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.eq("id",radarWechatAppSubscriptionOld.getId());
                updateWrapper.set("is_deleted",1);
                radarWechatAppSubscriptionMapper.update(null,updateWrapper);
            }
        }catch (Exception e){
            e.printStackTrace();
            return CommonRes.failed("取消订阅异常");
        }
        return CommonRes.ok("取消订阅成功");
    }


    @Override
    public CommonRes moreDevice() {
        String unionid = RecoupUtil.getCurrentUser().getUnionid();
        if(StringUtils.isEmpty(unionid)){
            return CommonRes.failed("获取用户信息有误！unionid为空");
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("unionid",unionid);
        WxDetailed wxDetailed =  wxDetailedMapper.selectOne(queryWrapper);
        if(wxDetailed==null){
            return CommonRes.failed("尚未关注清雷微信公众平台");
        }

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("open_id",wxDetailed.getOpenid());
        queryWrapper1.eq("is_deleted",0);
        List<RadarWechatApp> reseltList = radarWechatAppMapper.selectList(queryWrapper1);
        return  CommonRes.ok(reseltList);

    }

    public boolean isSnLegitimate(String snCode){
        Bed bed = bedService.getBedBySn(snCode);
        if(bed == null ){
            return  false;
        }
        if(bed.getTenantId()!= TenantContextHolder.getTenantId()){
            return  false;
        }
        return  true;
    }

}
